home *** CD-ROM | disk | FTP | other *** search
/ The 640 MEG Shareware Studio 2 / The 640 Meg Shareware Studio CD-ROM Volume II (Data Express)(1993).ISO / clang / cans2.zip / CANSWERS.TXT
Text File  |  1990-09-01  |  64KB  |  1,492 lines

  1. (86)    01 Sep 90  10:36:20
  2. By: Steve Summit
  3. To: All
  4. Re: Answers to Frequently Asked Questions (FAQ) on comp.lang.c
  5. St:
  6. ------------------------------------------------------------------------------
  7. @UFGATE newsin 1.27
  8. From: scs@adam.mit.edu (Steve Summit)
  9. Date: 1 Sep 90 04:04:35 GMT
  10. Organization: Thermal Technologies, Inc.
  11. Message-ID: <1990Sep1.040435.5598@athena.mit.edu>
  12. Newsgroups: comp.lang.c
  13.  
  14. Certain topics come up again and again on this newsgroup.  They are good
  15. questions, and the answers may not be immediately obvious, but each time
  16. they recur, much net bandwidth and reader time is wasted on repetitive
  17. responses, and on tedious corrections to the incorrect answers which are
  18. inevitably posted.
  19.  
  20. This article, which will be reposted periodically, attempts to answer
  21. these common questions definitively and succinctly, so that net
  22. discussion can move on to more constructive topics without continual
  23. regression to first principles.
  24.  
  25. This article does not, and cannot, provide an exhaustive discussion of
  26. all of the subtle points and counterarguments which could be mentioned
  27. with respect to these topics.  Cross-references to standard C
  28. publications have been provided, for further study by the interested and
  29. dedicated reader.  A few of the more perplexing and pervasive topics may
  30. be further explored in some in-depth minitreatises posted in conjunction
  31. with this article.
  32.  
  33. No mere newsgroup article can substitute for thoughtful perusal of a
  34. full-length language reference manual.  Anyone interested enough in C to
  35. be following this newsgroup should also be interested enough to read and
  36. study one or more such manuals, preferably several times.  Some vendors'
  37. compiler manuals are unfortunately inadequate; a few even perpetuate
  38. some of the myths which this article attempts to debunk.  Two invaluable
  39. references, which are an excellent addition to any serious programmer's
  40. library, are:
  41.  
  42.      The C Programming Language, by Brian W. Kernighan and Dennis M.
  43.      Ritchie.
  44.  
  45.      C: A Reference Manual, by Samuel P. Harbison and Guy L. Steele, Jr.
  46.  
  47. Both exist in several editions.  Andrew Koenig's book _C Traps and
  48. Pitfalls_ also covers many of the difficulties frequently discussed
  49. here.
  50.  
  51. If you have a question about C which is not answered in this article,
  52. please try to answer it by referring to these or other books, or to
  53. knowledgeable colleagues, before posing your question to the net at
  54. large.  There are many people on the net who are happy to answer
  55. questions, but the volume of repetitive answers posted to one question,
  56. as well as the growing numbers of questions as the net attracts more
  57. readers, can become oppressive.  If you have questions or comments
  58. prompted by this article, please reply by mail rather than following up
  59. -- this article is meant to decrease net traffic, not increase it.
  60.  
  61. This article is always being improved.  Your input is welcomed.  Send
  62. your comments to scs@adam.mit.edu and/or scs%adam.mit.edu@mit.edu; this
  63. article's From: line may be unuseable.
  64.  
  65. Herewith, some frequently-asked questions and their answers:
  66.  
  67. Null Pointers
  68.  
  69. 1.  What is this infamous null pointer, anyway?
  70.  
  71. A:  The language definition states that for each pointer type, there is
  72.     a special value -- the "null pointer" -- which is distinguishable
  73.     from all other pointer values and which is not the address of any
  74.     object.  That is, the address-of operator & will never "return" a
  75.     null pointer, nor will a successful call to malloc.  (malloc returns
  76.     a null pointer when it fails, and this is a typical use of null
  77.     pointers: as a "special" pointer value with some other meaning,
  78.     usually "not allocated" or "not pointing anywhere yet.")
  79.  
  80.     A null pointer is different from an uninitialized pointer.  A null
  81.     pointer is known not to point to any object; an uninitialized
  82.     pointer might point anywhere (that is, at some random object, or at
  83.     a garbage or unallocated address).  See also question 34.
  84.  
  85.     As mentioned in the definition above, there is a null pointer for
  86.     each pointer type, and the internal values of null pointers for
  87.     different types may be different.  Although programmers need not
  88.     know the internal values, the compiler must always be informed which
  89.     null pointer is required, so it can make the distinction if
  90.     necessary (see below).
  91.  
  92.     References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S
  93.     Sec. 5.3 p. 91; ANSI X3.159-1989 Sec. 3.2.2.3 .
  94.  
  95. 2.  How do I "get" a null pointer in my programs?
  96.  
  97. A:  According to the language definition, a constant 0 in a pointer
  98.     context is converted into a null pointer at compile time.  That is,
  99.     in an initialization, assignment, or comparison when one side is a
  100.     variable or expression of pointer type, the compiler can tell that a
  101.     constant 0 on the other side requests a null pointer, and generate
  102.     the correctly-typed null pointer value.  Therefore, the following
  103.     fragments are perfectly legal:
  104.  
  105.          char *p = 0;
  106.          if(p != 0)
  107.  
  108.     However, an argument being passed to a function is not necessarily
  109.     recognizable as a pointer context, and the compiler may not be able
  110.     to tell that an unadorned 0 "means" a null pointer.  For instance,
  111.     the Unix system call "execl" takes a variable-length, null pointer-
  112.     terminated list of character pointer arguments.  To generate a null
  113.     pointer in a function call context, an explicit cast is typically
  114.     required:
  115.  
  116.          execl("/bin/sh", "sh", "-c", "ls", (char *)0);
  117.  
  118.     If the (char *) cast were omitted, the compiler would not know to
  119.     pass a null pointer, and would pass an integer 0 instead.  (Note
  120.     that many Unix manuals get this example wrong.)
  121.  
  122.     When function prototypes are in scope, argument passing becomes an
  123.     "assignment context," and casts may safely be omitted, since the
  124.     prototype tells the compiler that a pointer is required, and of
  125.     which type, enabling it to correctly cast unadorned 0's.  Function
  126.     prototypes cannot provide the types for variable arguments in
  127.     variable-length argument lists, however, so explicit casts are still
  128.     required for those arguments.  It is safest always to cast null
  129.     pointer function arguments, to guard against varargs functions or
  130.     those without prototypes, to allow interim use of non-ANSI
  131.     compilers, and to demonstrate that you know what you are doing.
  132.  
  133.     Summary:
  134.  
  135.          unadorned 0 okay:        explicit cast required:
  136.  
  137.          initialization           function call,
  138.                                   no prototype in scope
  139.          assignments
  140.                                   variable argument to
  141.          comparisons              varargs function
  142.  
  143.          function call,
  144.          prototype in scope,
  145.          fixed argument
  146.  
  147.     References: K&R I Sec. A7.7 p. 190, Sec. A7.14 p. 192; K&R II Sec.
  148.     A7.10 p. 207, Sec. A7.17 p. 209; H&S Sec. 4.6.3 p. 72; ANSI X3.159-
  149.     1989 Sec. 3.2.2.3 .
  150.  
  151. 3.  But aren't pointers the same as ints?
  152.  
  153. A:  Not since the early days.  Attempting to push pointers into
  154.     integers, or build pointers out of integers, has always been
  155.     machine-dependent and unportable, and doing so is strongly
  156.     discouraged.  (Any object pointer may be cast to the "universal"
  157.     pointer type void *, or char * under a pre-ANSI compiler, when
  158.     heterogeneous pointers must be passed around.)
  159.  
  160.     References: K&R I Sec. 5.6 pp. 102-3; ANSI X3.159-1989 Sec. 3.3.4 .
  161.  
  162. 4.  What is NULL and how is it #defined?
  163.  
  164. A:  As a stylistic convention, many people prefer not to have unadorned
  165.     0's scattered throughout their programs.  For this reason, the
  166.     preprocessor macro NULL is #defined (by stdio.h or stddef.h), with
  167.     value 0 (or (void *)0, about which more later).  A programmer who
  168.     wishes to make explicit the distinction between 0 the integer and 0
  169.     the null pointer can then use NULL whenever a null pointer is
  170.     required.  This is a stylistic convention only; the preprocessor
  171.     turns NULL back to 0 which is then recognized by the compiler (in
  172.     pointer contexts) as before.  In particular, a cast may still be
  173.     necessary before NULL (as before 0) in a function call argument.
  174.     (The table under question 2 above applies for NULL as well as 0.)
  175.  
  176.     NULL should _only_ be used for pointers.  It should not be used when
  177.     another kind of 0 is required, even though it might work, because
  178.     doing so sends the wrong stylistic message.  (ANSI allows the
  179.     #definition of NULL to be (void *)0, which will not work in non-
  180.     pointer contexts.)  In particular, do not use NULL when the ASCII
  181.     null character (NUL) is desired.  Provide your own definition
  182.  
  183.          #define NUL '\0'
  184.  
  185.     if you must.
  186.  
  187.     References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S
  188.     Sec. 13.1 p. 283; ANSI X3.159-1989 Sec. 4.1.5 p. 99, Sec. 3.2.2.3
  189.     p. 38, Rationale Sec. 4.1.5 p. 74.
  190.  
  191. 5.  How should NULL be #defined on a machine which uses a nonzero bit
  192.     pattern as the internal representation of a null pointer?
  193.  
  194. A:  Programmers should never need to know the internal representation(s)
  195.     of null pointers, because they are normally taken care of by the
  196.     compiler.  If a machine uses a nonzero bit pattern for null
  197.     pointers, it is the compiler's responsibility to generate it when
  198.     the programmer requests, by writing "0" or "NULL," a null pointer.
  199.     Therefore #defining NULL as 0 on a machine for which internal null
  200.     pointers are nonzero is as valid as on any other, because the
  201.     compiler must (and can) still generate the machine's correct null
  202.     pointers in response to unadorned 0's seen in pointer contexts.
  203.  
  204. 6.  If NULL were defined as follows:
  205.          #define NULL (char *)0
  206.  
  207.     wouldn't that make function calls which pass an uncast NULL work?
  208.  
  209. A:  Not in general.  The problem is that there are machines which use
  210.     different internal representations for pointers to different types
  211.     of data.  The suggested #definition would make uncast NULL arguments
  212.     to functions expecting pointers to characters to work correctly, but
  213.     pointer arguments to other types would still be problematical, and
  214.     legal constructions such as
  215.  
  216.          FILE *fp = NULL;
  217.  
  218.     could fail.
  219.  
  220.     Nevertheless, ANSI C allows the alternate
  221.  
  222.          #define NULL (void *)0
  223.  
  224.     definition for NULL.  Besides helping incorrect programs to work
  225.     (but only on machines with all pointers the same, thus questionably
  226.     valid assistance) this definition may catch programs which use NULL
  227.     incorrectly (e.g. when the ASCII nul character was really intended).
  228.  
  229. 7.  Is the abbreviated pointer comparison "if(p)" to test for non-null
  230.     pointers valid?  What if the internal representation for null
  231.     pointers is nonzero?
  232.  
  233. A:  When C requires the boolean value of an expression (in the if,
  234.     while, for, and do statements, and with the &&, ||, !, and ?:
  235.     operators), a false value is produced when the expression compares
  236.     equal to zero, and a true value otherwise.  That is, whenever one
  237.     writes
  238.  
  239.          if(expr)
  240.  
  241.     where "expr" is any expression at all, the compiler essentially acts
  242.     as if it had been written as
  243.  
  244.          if(expr != 0)
  245.  
  246.     Substituting the trivial pointer expression "p" for "expr," we have
  247.  
  248.          if(p)      is equivalent to                 if(p != 0)
  249.  
  250.     and this is a comparison context, so the compiler can tell that the
  251.     (implicit) 0 is a null pointer, and use the correct value.  There is
  252.     no trickery involved here; compilers do work this way, and generate
  253.     identical code for both statements.  The internal representation of
  254.     a pointer does not matter.
  255.  
  256.     The boolean negation operator, !, can be described as follows:
  257.  
  258.          !expr      is essentially equivalent to     expr?0:1
  259.  
  260.     It is left as an exercise for the reader to show that
  261.  
  262.          if(!p)     is equivalent to                 if(p == 0)
  263.  
  264.     See also question 48.
  265.  
  266.     References: K&R II Sec. A7.4.7 p. 204; H&S Sec. 5.3 p. 91; ANSI
  267.     X3.159-1989 Secs. 3.3.3.3, 3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1,
  268.     and 3.6.5 .
  269.  
  270. 8.  If "NULL" and "0" are equivalent, which should I use?
  271.  
  272. A:  Many programmers believe that "NULL" should be used in all pointer
  273.     contexts, as a reminder that the value is to be thought of as a
  274.     pointer.  Others feel that the confusion surrounding "NULL" and "0"
  275.     is only compounded by hiding "0" behind a #definition, and prefer to
  276.     use unadorned "0" instead.  There is no one right answer.
  277.     C programmers must understand that "NULL" and "0" are
  278.     interchangeable and that an uncast "0" is perfectly acceptable in
  279.     initialization, assignment, and comparison contexts.  Any usage of
  280.     "NULL" (as opposed to "0") should be considered a gentle reminder
  281.     that a pointer is involved; programmers should not depend on it
  282.     (either for their own understanding or the compiler's) for
  283.     distinguishing pointer 0's from integer 0's.  Again, NULL should not
  284.     be used for other than pointers.
  285.  
  286.     References: K&R II Sec. 5.4 p. 102.
  287.  
  288. 9.  But wouldn't it be better to use NULL (rather than 0) in case the
  289.     value of NULL changes, perhaps on a machine with nonzero null
  290.     pointers?
  291.  
  292. A:  No.  Although preprocessor macros are often used in place of numbers
  293.     because the numbers might change, this is _not_ the reason that NULL
  294.     is used in place of 0.  The language guarantees that source-code 0's
  295.     (in pointer contexts) generate null pointers.  NULL is used only as
  296.     a stylistic convention.
  297.  
  298. 10. But I once used a compiler that wouldn't work unless NULL was used.
  299.  
  300. A:  This compiler was broken.  In general, making decisions about a
  301.     language based on the behavior of one particular compiler is likely
  302.     to be counterproductive.
  303.  
  304. 11. I'm confused.  NULL is guaranteed to be 0, but the null pointer is
  305.     not?
  306.  
  307. A:  A "null pointer" (written in lower case in this article) is a
  308.     language concept whose particular internal value does not matter.
  309.     (On some machines the internal value is 0; on others it is not.)  A
  310.     "null pointer" is requested in source code with the character "0".
  311.     "NULL" (always in capital letters) is a preprocessor macro, which is
  312.     always #defined as 0 (or (void *)0).
  313.  
  314.     When the term "null" or "NULL" is casually used, one of several
  315.     things may be meant:
  316.  
  317.     1.   The conceptual null pointer, the abstract language concept
  318.          defined in question 1.  It is implemented with...
  319.  
  320.     2.   The internal (or run-time) representation of a null pointer,
  321.          which may be different for different pointer types.  The actual
  322.          values should be of concern only to compiler writers.  Authors
  323.          of C programs never see them, since they use...
  324.  
  325.     3.   The source code syntax for null pointers, which is the single
  326.          character "0".  It is often hidden behind...
  327.  
  328.     4.   The NULL macro, which is #defined to be "0" or "(void *)0".
  329.          Finally, as a red herring, we have
  330.  
  331.     5.   The ASCII null character (NUL), which does have all bits zero,
  332.          but has no relation to the null pointer except in name.
  333.  
  334.     This article always uses the phrase "null pointer" for sense 1, the
  335.     character "0" for sense 3, and the capitalized word "NULL" for
  336.     sense 4.
  337.  
  338. 12. Why is there so much confusion surrounding null pointers?  Why do
  339.     these questions come up so often?
  340.  
  341. A:  C programmers traditionally like to know more than they need to
  342.     about the underlying machine implementation.  The construct
  343.     "if(p == 0)" is easily misread as calling for conversion of p to an
  344.     integral type, rather than 0 to a pointer type, before the
  345.     comparison.  The fact that null pointers are represented both in
  346.     source code, and internally to most machines, as zero invites
  347.     unwarranted assumptions.  The fact that a preprocessor macro (NULL)
  348.     is often used suggests that this is done because the value might
  349.     change later, or on some weird machine.  Finally, the distinction
  350.     between the several uses of the term "null" (listed above) is often
  351.     overlooked.
  352.  
  353.     One good way to wade out of the confusion is to imagine that C had a
  354.     keyword (perhaps "nil", like Pascal) with which null pointers were
  355.     requested.  The compiler could either turn "nil" into the correct
  356.     type of null pointer, when it could determine the type from the
  357.     source code (as it does with 0's in reality), or complain when it
  358.     could not.  Now, in fact, in C the keyword for a null pointer is not
  359.     "nil" but "0", which works almost as well, except that an uncast "0"
  360.     in a non-pointer context generates an integer zero.  If the null
  361.     pointer keyword were "nil" the compiler could emit an error message
  362.     for an ambiguous usage, but since it is "0" the compiler may end up
  363.     emitting incorrect code.
  364.  
  365. 13. I'm still confused.  I just can't understand all this null pointer
  366.     stuff.
  367.  
  368. A:  Follow these two simple rules:
  369.  
  370.     1.   When you want to refer to a null pointer in source code, use
  371.          "0" or "NULL".
  372.  
  373.     2.   If the usage of "0" or "NULL" is in a function call, cast it to
  374.          the pointer type expected by the function being called.
  375.  
  376.     The rest of the discussion has to do with other people's
  377.     misunderstandings, or with the internal representation of null
  378.     pointers, which you shouldn't need to know.
  379.  
  380. Arrays and Pointers
  381.  
  382. 14. I had the declaration char a[5] in one source file, and in another I
  383.     declared extern char *a.  Why didn't it work?
  384.  
  385. A:  The declaration extern char *a simply does not match the actual
  386.     definition.  The type "pointer-to-type-T" is not the same as
  387.     "array-of-type-T."  Use extern char a[].
  388.  
  389. 15. But I heard that char a[] was identical to char *a.
  390.  
  391. A:  This identity (that a pointer declaration is interchangeable with an
  392.     array declaration, usually unsized) holds _only_ for formal
  393.     parameters to functions.  This identity is related to the fact that
  394.     arrays "turn into" pointers in expressions.  That is, when an array
  395.     name is mentioned in an expression, it is converted immediately into
  396.     a pointer to the array's first element.  Therefore, an array is
  397.     never passed to a function; rather a pointer to its first element is
  398.     passed instead.  Allowing pointer parameters to be declared as
  399.     arrays is a simply a way of making it look as though the array was
  400.     actually being passed.  Some programmers prefer, as a matter of
  401.     style, to use this syntax to indicate that the pointer parameter is
  402.     expected to point to the start of an array rather than to a single
  403.     value.
  404.  
  405.     Since functions can never receive arrays as parameters, any
  406.     parameter declarations which "look like" arrays, e.g.
  407.  
  408.          f(a)
  409.          char a[];
  410.  
  411.     are treated as if they were pointers, since that is what the
  412.     function will receive if an array is passed:
  413.  
  414.          f(a)
  415.          char *a;
  416.  
  417.     To repeat, however, this conversion holds only within function
  418.     formal parameter declarations, nowhere else.  If this conversion
  419.     confuses you, don't use it; many people have concluded that the
  420.     confusion it causes outweighs the small advantage of having the
  421.     declaration "look like" the call and/or the uses within the
  422.     function.
  423.  
  424.     References: K&R I Sec. 5.3 p. 95, Sec. A10.1 p. 205; K&R II Sec. 5.3
  425.     p. 100, Sec. A8.6.3 p. 218, Sec. A10.1 p. 226; H&S Sec. 5.4.3 p. 96;
  426.     ANSI X3.159-1989 Sec. 3.5.4.3, Sec. 3.7.1 .
  427.  
  428. 16. So what is meant by the "equivalence of pointers and arrays" in C?
  429.  
  430. A:  Perhaps no aspect of C is more confusing than pointers, and the
  431.     confusion is compounded by statements like the one above.  Saying
  432.     that arrays and pointers are "equivalent" does not by any means
  433.     imply that they are interchangeable.  (The fact that, as formal
  434.     parameters to functions, array-style and pointer-style declarations
  435.     are in fact interchangeable does nothing to reduce the confusion.)
  436.  
  437.     "Equivalence" refers to the fact (mentioned above) that arrays decay
  438.     into pointers within expressions, and that pointers and arrays can
  439.     both be dereferenced using array-like subscript notation.  That is,
  440.     if we have
  441.  
  442.          char a[10];
  443.          char *p;
  444.          int i;
  445.  
  446.     we can refer to a[i] and p[i].  (That pointers can be subscripted
  447.     like arrays is hardly surprising, since arrays have decayed into
  448.     pointers by the time they are subscripted.)
  449.  
  450.     References: K&R I Sec. 5.3 pp. 93-6; K&R II Sec. 5.3 p. 99; H&S Sec.
  451.     5.4.1 p. 93; ANSI X3.159-1989 Sec. 3.3.2.1, Sec. 3.3.6 .
  452.  
  453. 17. My compiler complained when I passed a two-dimensional array to a
  454.     routine expecting a pointer to a pointer.
  455.  
  456. A:  The rule by which arrays decay into pointers is not applied
  457.     recursively.  An array of arrays (i.e. a two-dimensional array in C)
  458.     decays into a pointer to an array, not a pointer to a pointer.
  459.     Pointers to arrays are confusing, and it is best to avoid them.
  460.     (The confusion is heightened by incorrect compilers, including some
  461.     versions of pcc and pcc-derived lint's, which incorrectly accept
  462.     assignments of multi-dimensional arrays to multi-level pointers.)
  463.     If you are passing a two-dimensional array to a function:
  464.  
  465.          int array[YSIZE][XSIZE];
  466.          f(array);
  467.  
  468.     the function's declaration should match:
  469.          f(int a[][XSIZE]) {...}
  470.     or
  471.          f(int (*a)[XSIZE]) {...}
  472.  
  473.     In the first declaration, the compiler performs the usual implicit
  474.     rewriting of "array of array" to "pointer to array;" in the second
  475.     form the pointer declaration is explicit.  The called function does
  476.     not care how big the array is, but it must know its shape, so the
  477.     "column" dimension XSIZE must be included.  In both cases the number
  478.     of "rows" is irrelevant, and omitted.
  479.  
  480.     If a function is already declared as accepting a pointer to a
  481.     pointer, an intermediate pointer would need to be used when
  482.     attempting to call it with a two-dimensional array:
  483.  
  484.          int *ip = &a[0][0];
  485.          g(&ip);
  486.          ...
  487.          g(int **ipp) {...}
  488.  
  489.     Note that this usage is liable to be misleading (if not incorrect),
  490.     since the array has been "flattened" (its shape has been lost).
  491.  
  492. 18. How do I declare a pointer to an array?
  493.  
  494. A:  Usually, you don't want one.  Think about using a pointer to one of
  495.     the array's elements instead.  Arrays of type T decay into pointers
  496.     to type T, which is convenient; subscripting or incrementing the
  497.     resultant pointer accesses the individual members of the array.
  498.     True pointers to arrays, when subscripted or incremented, step over
  499.     entire arrays, and are generally only useful when operating on
  500.     multidimensional arrays.  (See the question above.)
  501.  
  502. 19. How can I dynamically allocate a multidimensional array?
  503.  
  504. A:  It is usually best to allocate an array of pointers, and then
  505.     initialize each pointer to a dynamically-allocated "row." The
  506.     resulting "ragged" array often saves space, although it may not be
  507.     contiguous in memory as a real array would be.
  508.  
  509.          int **array = (int **)malloc(nrows * sizeof(int *));
  510.          for(i = 0; i < nrows; i++)
  511.                  array[i] = (int *)malloc(ncolumns * sizeof(int));
  512.  
  513.     (In "real" code, of course, malloc's return value should be
  514.     checked.)
  515.  
  516.     You can keep the array's contents contiguous, while losing the
  517.     ability to have rows of varying and different lengths, with a bit of
  518.     explicit pointer arithmetic:
  519.  
  520.          int **array = (int **)malloc(nrows * sizeof(int *));
  521.          array[0] = (int *)malloc(nrows * ncolumns * sizeof(int));
  522.          for(i = 1; i < nrows; i++)
  523.                  array[i] = array[0] + i * ncolumns;
  524.  
  525.     In either case, the elements of the dynamic array can be accessed
  526.     with normal-looking array subscripts: array[i][j].
  527.  
  528.     If the double indirection implied by the above scheme is for some
  529.     reason unacceptable, you can simulate a two-dimensional array with a
  530.     single, dynamically-allocated one-dimensional array:
  531.  
  532.          int *array = (int *)malloc(nrows * ncolumns * sizeof(int));
  533.  
  534.     However, you must now perform subscript calculations manually,
  535.     accessing array[i, j] with array[i * ncolumns + j].  (A macro can
  536.     hide the explicit calculation, but invoking it then requires
  537.     parentheses and commas which don't look exactly like
  538.     multidimensional array subscripts.)
  539.  
  540. Order of Evaluation
  541.  
  542. 20. Under my compiler, the code
  543.  
  544.          int i = 7;
  545.          printf("%d\n", i++ * i++);
  546.  
  547.     prints 49.  Regardless of the order of evaluation, shouldn't it
  548.     print 56?
  549.  
  550. A:  Although the postincrement and postdecrement operators ++ and --
  551.     perform the operations after yielding the former value, many people
  552.     misunderstand the implication of "after." It is _not_ guaranteed
  553.     that the operation is performed immediately after giving up the
  554.     previous value and before any other part of the expression is
  555.     evaluated.  It is merely guaranteed that the update will be
  556.     performed sometime before the expression is considered "finished"
  557.     (before the next "sequence point," in ANSI C's terminology).
  558.  
  559.     In the example, the compiler chose to multiply the previous value by
  560.     itself and to perform both increments afterwards.
  561.  
  562.     The order of other embedded side effects is similarly undefined.
  563.     For example, the expression i + (i = 2) may or may not have the
  564.     value 4.  ANSI allows compilers to reject code which contains such
  565.     ambiguous or undefined side effects.
  566.  
  567.     References: K&R I Sec. 2.12 p. 50; K&R II Sec. 2.12 p. 54; ANSI
  568.     X3.159-1989 Sec. 3.3 .
  569.  
  570. 21. But what about the &&, ||, ?:, and comma operators?
  571.     I see code like "if((c = getchar()) == EOF || c == '\n')" ...
  572.  
  573. A:  There is a special exception for those operators; each of them does
  574.     imply a sequence point (i.e. left-to-right evaluation is
  575.     guaranteed).
  576.  
  577.     References: ANSI X3.159-1989 Secs. 3.3.2.2, 3.3.13, 3.3.14, 3.3.15 .
  578.  
  579. ANSI C
  580.  
  581. 22. What is the "ANSI C Standard?"
  582.  
  583. A:  In 1983, the American National Standards Institute commissioned a
  584.     committee, X3J11, to standardize the C language.  After a long and
  585.     arduous process, this C standard was finally ratified as an American
  586.     National Standard, X3.159-1989, on December 14, 1989, and published
  587.     in the spring of 1990.  For the most part, ANSI C standardizes
  588.     existing practice, with a few additions from C++ (most notably
  589.     function prototypes) and support for multinational character sets
  590.     (including the much-lambasted trigraph sequences for transfer of
  591.     source code between machines with deficient or multinational
  592.     character sets).  The ANSI C standard also formalizes the C run-time
  593.     library support routines, an unprecedented effort.
  594.  
  595. 23. How can I get a copy of the ANSI C standard?
  596.  
  597. A:  Copies are available from
  598.  
  599.         American National Standards Institute
  600.         1430 Broadway
  601.         New York, NY  10018
  602.         (212) 642-4900
  603.  
  604.     or
  605.  
  606.         Global Engineering Documents
  607.         2805 McGaw Avenue
  608.         Irvine, CA  92714
  609.         (714) 261-1455
  610.  
  611.     The cost is approximately $50.00, plus $6.00 shipping.  Quantity
  612.     discounts are available.
  613.  
  614. 24. Does anyone have a tool for converting old-style C programs to ANSI
  615.     C, or for automatically generating prototypes?
  616.  
  617. A:  There are several such programs, many in the public domain.  Check
  618.     your nearest comp.sources archive.  (See also questions 61 and 62.)
  619.  
  620. 25. My ANSI compiler complains about a mismatch when it sees
  621.  
  622.          extern int func(float);
  623.          int func(x)
  624.          float x;
  625.          {...
  626.  
  627. A:  You have mixed the new-style declaration "extern int func(float);"
  628.     with the old-style definition "int func(x) float x;".  Old C (and
  629.     ANSI C, in the absence of prototypes) silently promotes floats to
  630.     doubles when passing them as arguments, and makes a corresponding
  631.     silent change to formal parameter declarations, so the old-style
  632.     definition actually says that func takes a double.
  633.  
  634.     The problem can be fixed either by using new-style syntax
  635.     consistently in the definition:
  636.  
  637.          int func(float x) { ... }
  638.  
  639.     or by changing the new-style prototype declaration to match the
  640.     old-style definition:
  641.  
  642.          extern int func(double);
  643.  
  644.     (In this case, it would be clearest to change the old-style
  645.     definition to use double as well).
  646.  
  647.     References: ANSI X3.159-1989 Sec. 3.3.2.2 .
  648.  
  649. C Preprocessor
  650.  
  651. 26. How can I write a macro to swap two values?
  652.  
  653. A:  There is no good answer to this question.  If the values are
  654.     integers, a well-known trick using exclusive-OR could perhaps be
  655.     used, but it will not work for floating-point values or pointers.
  656.     If the macro is intended to be used on values of arbitrary type (the
  657.     usual goal), it cannot use a temporary, since it doesn't know what
  658.     type of temporary it needs, and standard C does not provide a typeof
  659.     operator.  (GNU C does.)
  660.  
  661.     The best all-around solution is probably to forget about using a
  662.     macro.  If you're worried about the use of an ugly temporary, and
  663.     know that your machine provides an exchange instruction, convince
  664.     your compiler vendor to recognize the standard three-assignment swap
  665.     idiom in the optimization phase.  Alternatively, use a language
  666.     which supports multiple, parallel assignment (a,b := b,a).
  667.  
  668. 27. I'm getting strange syntax errors inside code which I've #ifdeffed
  669.     out.
  670.  
  671. A:  Under ANSI C, the text inside a "turned off" #if, #ifdef, or #ifndef
  672.     must still consist of "valid preprocessing tokens."  This means that
  673.     there must be no unterminated comments or quotes (note particularly
  674.     that an apostrophe within a contracted word looks like the beginning
  675.     of a character constant) and no newlines inside quotes.  Therefore,
  676.     natural-language comments should always be written between the
  677.     "official" comment delimiters /* and */.
  678.  
  679. 28. How can I write a cpp macro which takes a variable number of
  680.     arguments?
  681.  
  682.     One popular trick is to define the macro with a single argument, and
  683.     call it with a double set of parentheses, which appear to the
  684.     compiler to indicate a single argument:
  685.  
  686.          #define DEBUG(args) {printf("DEBUG: ");printf args;}
  687.  
  688.          if(n != 0) DEBUG(("n is %d\n", n));
  689.  
  690.     The obvious disadvantage to this trick is that the caller must
  691.     always remember to use the extra parentheses.  (It is often best to
  692.     use a bona-fide function, which can take a variable number of
  693.     arguments in a well-defined way, rather than a macro.  See questions
  694.     29 and 30 below.)
  695.  
  696. Variable-Length Argument Lists
  697.  
  698. 29. How can I write a function that takes a variable number of
  699.     arguments?
  700.  
  701. A:  Use varargs or stdarg.
  702.  
  703.     Here is a function which concatenates an arbitrary number of strings
  704.     into malloc'ed memory, using stdarg:
  705.  
  706.          #include <stddef.h>             /* for NULL */
  707.          #include <stdarg.h>             /* for va_ stuff */
  708.          #include <string.h>             /* for strcat et al */
  709.          #include <stdlib.h>             /* for malloc */
  710.  
  711.          extern char *malloc();          /* redundant */
  712.  
  713.          /* VARARGS1 */
  714.  
  715.          char *
  716.          vstrcat(char *first, ...)
  717.          {
  718.                  int len = 0;
  719.                  char *retbuf;
  720.                  va_list argp;
  721.                  char *p;
  722.  
  723.                  if(first == NULL)
  724.                          return NULL;
  725.  
  726.                  len = strlen(first);
  727.  
  728.                  va_start(argp, first);
  729.  
  730.                  while((p = va_arg(argp, char *)) != NULL)
  731.                          len += strlen(p);
  732.  
  733.                  va_end(argp);
  734.  
  735.                  retbuf = malloc(len + 1);       /* +1 for trailing \0 */
  736.  
  737.                  if(retbuf == NULL)
  738.                          return NULL;
  739.  
  740.                  (void)strcpy(retbuf, first);
  741.  
  742.                  va_start(argp, first);
  743.  
  744.                  while((p = va_arg(argp, char *)) != NULL)
  745.                          (void)strcat(retbuf, p);
  746.  
  747.                  va_end(argp);
  748.  
  749.                  return retbuf;
  750.          }
  751.  
  752.     Usage is something like
  753.  
  754.          char *str = vstrcat("Hello, ", "world!", (char *)NULL);
  755.  
  756.     Note the cast on the last argument.  (Also note that the caller must
  757.     free the returned, malloc'ed storage.)
  758.  
  759.     Using the older varargs package, rather than stdarg, requires a few
  760.     changes which are not discussed here, in the interests of brevity.
  761.     See the next question for hints.
  762.  
  763.     References: K&R II Sec. 7.3 p. 155, Sec. B7 p. 254; H&S Sec. 13.4
  764.     pp. 286-9; ANSI X3.159-1989 Secs. 4.8 through 4.8.1.3 .
  765.  
  766. 30. How can I write a function that takes a format string and a variable
  767.     number of arguments, like printf, and passes them to printf to do
  768.     most of the work?
  769.  
  770. A:  Use vprintf, vfprintf, or vsprintf.
  771.  
  772.     Here is an "error" routine which prints an error message, preceded
  773.     by the string "error: " and terminated with a newline:
  774.  
  775.          #include <stdio.h>
  776.          #include <stdarg.h>
  777.  
  778.          void
  779.          error(char *fmt, ...)
  780.          {
  781.                  va_list argp;
  782.                  fprintf(stderr, "error: ");
  783.                  va_start(argp, fmt);
  784.                  vfprintf(stderr, fmt, argp);
  785.                  va_end(argp);
  786.                  fprintf(stderr, "\n");
  787.          }
  788.  
  789.     To use varargs, instead of stdarg, change the function header to:
  790.  
  791.          void error(va_alist)
  792.          va_dcl
  793.          {
  794.                  char *fmt;
  795.  
  796.     change the va_start line to
  797.  
  798.          va_start(argp);
  799.  
  800.     and add the line
  801.  
  802.          fmt = va_arg(argp, char *);
  803.  
  804.     between the calls to va_start and vfprintf.  (Note that there is no
  805.     semicolon after va_dcl.)
  806.  
  807.     References: K&R II Sec. 8.3 p. 174, Sec. B1.2 p. 245; H&S Sec. 17.12
  808.     p. 337; ANSI X3.159-1989 Secs. 4.9.6.7, 4.9.6.8, 4.9.6.9 .
  809.  
  810. 31. How can I write a function analogous to scanf?
  811.  
  812. A:  Unfortunately, vscanf and the like are not standard.  You're on your
  813.     own.
  814.  
  815. 32. How can I discover how many arguments a function was actually called
  816.     with?
  817.  
  818. A:  This information is not available to a portable program.  Some
  819.     systems have a nonstandard nargs() function available, but its use
  820.     is questionable, since it typically returns the number of words
  821.     pushed, not the number of arguments.  (Floating point values and
  822.     structures are usually passed as several words.)
  823.  
  824.     Any function which takes a variable number of arguments must be able
  825.     to determine from the arguments themselves how many of them there
  826.     are.  printf-like functions do this by looking for formatting
  827.     specifiers (%d and the like) in the format string (which is why
  828.     these functions fail badly if the format string does not match the
  829.     argument list).  Another common technique (useful when the arguments
  830.     are all of the same type) is to use a sentinel value (often 0, -1,
  831.     or an appropriately-cast null pointer) at the end of the list (see
  832.     the vstrcat and execl examples under questions 29 and 2 above).
  833.  
  834. 33. How can I write a function which takes a variable number of
  835.     arguments and passes them to some other function (which takes a
  836.     variable number of arguments)?
  837.  
  838. A:  In general, you cannot.  You must provide a version of that other
  839.     function which accepts a va_list pointer, as does vfprintf in the
  840.     example above.  If the arguments must be passed directly as actual
  841.     arguments (not indirectly through a va_list pointer) to another
  842.     function which is itself variadic (for which you do not have the
  843.     option of creating an alternate, va_list-accepting version) no
  844.     portable solution is possible.  (The problem can often be solved by
  845.     resorting to machine-specific assembly language.)
  846.  
  847. Memory Allocation
  848.  
  849. 34. Why doesn't this program work?
  850.  
  851.          main()
  852.          {
  853.                  char *answer;
  854.                  printf("Type something:\n");
  855.                  gets(answer);
  856.                  printf("You typed \"%s\"\n", answer);
  857.          }
  858.  
  859. A:  The pointer variable "answer," which is handed to the gets function
  860.     as the location into which the response should be stored, has not
  861.     been set to point to any valid storage.  It is an uninitialized
  862.     variable, just as is the variable i in this example:
  863.  
  864.          main()
  865.          {
  866.                  int i;
  867.                  printf("i = %d\n", i);
  868.          }
  869.  
  870.     That is, we cannot say where the pointer "answer" points.  (Since
  871.     local variables are not initialized, and typically contain garbage,
  872.     it is not even guaranteed that "answer" starts out as a null
  873.     pointer.)
  874.  
  875.     The simplest way to correct the question-asking program is to use a
  876.     local array, instead of a pointer, and let the compiler worry about
  877.     allocation:
  878.  
  879.          #include <stdio.h>
  880.          main()
  881.          {
  882.                  char answer[100];
  883.                  printf("Type something:\n");
  884.                  fgets(answer, 100, stdin);
  885.                  printf("You typed \"%s\"\n", answer);
  886.          }
  887.  
  888.     Note that this example also uses fgets instead of gets (always a
  889.     good idea), so that the size of the array can be specified, so that
  890.     fgets will not overwrite the end of the array if the user types an
  891.     overly-long line.  (Unfortunately, gets and fgets differ in their
  892.     treatment of the trailing \n.)  It would also be possible to use
  893.     malloc to allocate the answer buffer, and/or to parameterize its
  894.     size (#define ANSWERSIZE 100).
  895.  
  896. 35. You can't use dynamically-allocated memory after you free it, can
  897.     you?
  898.  
  899. A:  No.  Some early man pages for malloc stated that the contents of
  900.     freed memory was "left undisturbed;" this ill-advised guarantee is
  901.     not universal and is not required by ANSI.
  902.  
  903.     Few programmers would use the contents of freed memory deliberately,
  904.     but it is easy to do so accidentally.  Consider the following
  905.     (correct) code for freeing a singly-linked list:
  906.  
  907.          struct list *listp, *nextp;
  908.          for(listp = base; listp != NULL; listp = nextp) {
  909.                  nextp = listp->next;
  910.                  free((char *)listp);
  911.          }
  912.  
  913.     and notice what would happen if the more-obvious loop iteration
  914.     expression listp = listp->next were used, without the temporary
  915.     nextp pointer.
  916.  
  917. 36. What is alloca and why is its use discouraged?
  918.  
  919. A:  alloca allocates memory which is automatically freed when the
  920.     function from which alloca was called returns.  That is, memory
  921.     allocated with alloca is local to a particular function's "stack
  922.     frame" or context.
  923.  
  924.     alloca cannot be written portably, and is difficult to implement on
  925.     machines without a stack.  Its use is problematical (and the obvious
  926.     implementation on a stack-based machine fails) when its return value
  927.     is passed directly to another function, as in
  928.     fgets(alloca(100), stdin, 100).
  929.  
  930.     For these reasons, alloca cannot be used in programs which must be
  931.     widely portable, no matter how useful it might be.
  932.  
  933. Structures
  934.  
  935. 37. I heard that structures could be assigned to variables and passed to
  936.     and from functions, but K&R I says not.
  937.  
  938. A:  What K&R I said was that the restrictions on struct operations would
  939.     be lifted in a forthcoming version of the compiler, and in fact
  940.     struct assignment and passing were fully functional in Ritchie's
  941.     compiler even as K&R I was being published.  Although a few early C
  942.     compilers lacked struct assignment, all modern compilers support it,
  943.     and it is part of the ANSI C standard, so there should be no
  944.     reluctance to use it.
  945.  
  946.     References: K&R I Sec. 6.2 p. 121; K&R II Sec. 6.2 p. 129; H&S Sec.
  947.     5.6.2 p. 103; ANSI X3.159-1989 Secs. 3.1.2.5, 3.2.2.1, 3.3.16 .
  948.  
  949. 38. How does struct passing and returning work?
  950.  
  951. A:  When structures are passed as arguments to functions, the entire
  952.     struct is pushed on the stack, which may involve significant
  953.     overhead for large structures.  It may be preferable in such cases
  954.     to pass a pointer to the structure instead.
  955.  
  956.     Structures are returned from functions either in a special, static
  957.     place (which may make struct-valued functions nonreentrant) or in a
  958.     location pointed to by an extra, "hidden" argument to the function.
  959.  
  960. 39. The following program works correctly, but it dumps core after it
  961.     finishes.  Why?
  962.  
  963.          struct list
  964.                  {
  965.                  char *item;
  966.                  struct list *next;
  967.                  }
  968.  
  969.          /* Here is the main program. */
  970.  
  971.          main(argc, argv)
  972.          ...
  973.  
  974. A:  A missing semicolon causes the compiler to believe that main returns
  975.     a struct list.  (The connection is hard to see because of the
  976.     intervening comment.)  When struct-valued functions are implemented
  977.     by adding a hidden return pointer, the generated code tries to store
  978.     a struct with respect to a pointer which was not actually passed (in
  979.     this case, by the C start-up code).  Attempting to store a structure
  980.     into memory pointed to by the argc or argv value on the stack (where
  981.     the compiler expected to find the hidden return pointer) causes the
  982.     core dump.
  983.  
  984. 40. Why can't you compare structs?
  985.  
  986. A:  There is no reasonable way for a compiler to implement struct
  987.     comparison which is consistent with C's low-level flavor.  A byte-
  988.     by-byte comparison could be invalidated by random bits present in
  989.     unused "holes" in the structure (such padding is used to keep the
  990.     alignment of later fields correct).  A field-by-field comparison
  991.     would require unacceptable amounts of repetitive, in-line code for
  992.     large structures.  Either method would not necessarily "do the right
  993.     thing" with pointer fields: oftentimes, equality should be judged by
  994.     equality of the things pointed to rather than strict equality of the
  995.     pointers themselves.
  996.  
  997.     If you want to compare two structures, you must write your own
  998.     function to do so.  C++ (among other languages) would let you
  999.     arrange for the == operator to map to your function.
  1000.  
  1001.     References: K&R II Sec. 6.2 p. 129; H&S Sec. 5.6.2 p. 103.
  1002.  
  1003. 41. How can I determine the byte offset of a field within a structure?
  1004.  
  1005. A:  ANSI C defines the offsetof macro, which should be used if
  1006.     available.  If you don't have it, a suggested implementation is
  1007.  
  1008.          #define offsetof(type, mem) ((size_t) \
  1009.                  ((char *)&((type *) 0)->mem - (char *)((type *) 0)))
  1010.  
  1011.     This implementation is not 100% portable; some compilers may
  1012.     legitimately refuse to accept it.
  1013.  
  1014.     See the next question for a usage hint.
  1015.  
  1016.     References: ANSI X3.159-1989 Sec. 4.1.5 .
  1017.  
  1018. 42. How can I access structure fields by name at run time?
  1019.  
  1020. A:  Build a table of names and offsets, using the offsetof() macro.  The
  1021.     offset of field b in struct a is
  1022.  
  1023.          offsetof(struct a, b)
  1024.  
  1025.     If structp is a pointer to an instance of this structure, and b is
  1026.     an int field with offset as computed above, b's value can be set
  1027.     indirectly with
  1028.  
  1029.          *(int *)((char *)structp + offset) = value;
  1030.  
  1031. Declarations
  1032.  
  1033. 43. I can't seem to define a linked list node which contains a pointer
  1034.     to itself.  I tried
  1035.  
  1036.          typedef struct
  1037.                  {
  1038.                  char *item;
  1039.                  NODEPTR next;
  1040.                  } NODE, *NODEPTR;
  1041.  
  1042.     but the compiler gave me error messages.  Can't a struct in C
  1043.     contain a pointer to itself?
  1044.  
  1045. A:  Structs in C can certainly contain pointers to themselves; the
  1046.     discussion and example in section 6.5 of K&R make this clear.  The
  1047.     problem is that the example above attempts to hide the struct
  1048.     pointer behind a typedef, which is not complete at the time it is
  1049.     used.  First, rewrite it without a typedef:
  1050.  
  1051.          struct node
  1052.                  {
  1053.                  char *item;
  1054.                  struct node *next;
  1055.                  };
  1056.  
  1057.     Then, if you feel you must use typedefs, define them after the fact:
  1058.  
  1059.          typedef struct node NODE, *NODEPTR;
  1060.  
  1061.     Alternatively, define the typedefs first (using the line just above)
  1062.     and follow it with the full definition of struct node, which can
  1063.     then use the NODEPTR typedef for the "next" field.
  1064.  
  1065.     References: K&R I Sec. 6.5 p. 101; K&R II Sec. 6.5 p. 139; H&S Sec.
  1066.     5.6.1 p. 102; ANSI X3.159-1989 Sec. 3.5.2.3 .
  1067.  
  1068. 44. How can I define a pair of mutually referential structures?  I tried
  1069.  
  1070.          typedef struct
  1071.                  {
  1072.                  int structafield;
  1073.                  STRUCTB *bpointer;
  1074.                  } STRUCTA;
  1075.  
  1076.          typedef struct
  1077.                  {
  1078.                  int structbfield;
  1079.                  STRUCTA *apointer;
  1080.                  } STRUCTB;
  1081.  
  1082.     but the compiler doesn't know about STRUCTB when it is used in
  1083.     struct a.
  1084.  
  1085. A:  Again, the problem is not the pointers but the typedefs.  First,
  1086.     define the two structures without using typedefs:
  1087.  
  1088.          struct a
  1089.                  {
  1090.                  int structafield;
  1091.                  struct b *bpointer;
  1092.                  };
  1093.  
  1094.          struct b
  1095.                  {
  1096.                  int structbfield;
  1097.                  struct a *apointer;
  1098.                  };
  1099.  
  1100.     The compiler can accept the field declaration struct b *bpointer
  1101.     within struct a, even though it has not yet heard of struct b.
  1102.     Occasionally it is necessary to precede this couplet with the empty
  1103.     declaration
  1104.  
  1105.          struct b;
  1106.  
  1107.     to mask the declaration (if in an inner scope) from a different
  1108.     struct b in an outer scope.
  1109.  
  1110.     Again, the typedefs could also be defined before, and then used
  1111.     within, the definitions for struct a and struct b.  Problems arise
  1112.     only when an attempt is made to define and use a typedef within the
  1113.     same declaration.
  1114.  
  1115.     References: H&S Sec. 5.6.1 p. 102; ANSI X3.159-1989 Sec. 3.5.2.3 .
  1116.  
  1117. 45. How do I declare a pointer to a function returning a pointer to a
  1118.     double?
  1119.  
  1120. A:  There are at least three answers to this question:
  1121.  
  1122.     1.   double *(*p)();
  1123.  
  1124.     2.   Build it up in stages, using typedefs:
  1125.               typedef double *pd;      /* pointer to double */
  1126.               typedef pd fpd();        /* func returning ptr to double */
  1127.               typedef fpd *pfpd;       /* ptr to func ret ptr to double */
  1128.               pfpd p;
  1129.  
  1130.     3.   Use the cdecl program, which turns English into C and vice
  1131.          versa:
  1132.  
  1133.               $ cdecl
  1134.               cdecl> declare p as pointer to function returning pointer to
  1135. double
  1136.               double *(*p)();
  1137.               cdecl>
  1138.  
  1139.          cdecl can also explain complicated declarations, help with
  1140.          casts, and indicate which set of parentheses the arguments go
  1141.          in (for complicated function definitions).
  1142.  
  1143.     References: H&S Sec. 5.10.1 p. 116.
  1144.  
  1145. 46. So where can I get cdecl?
  1146.  
  1147. A:  Several public-domain versions are available.  One is in volume 14
  1148.     of comp.sources.unix .  (Commercial versions may also be available,
  1149.     at least one of which was shamelessly lifted from the public domain
  1150.     copy submitted by Graham Ross, one of cdecl's originators.)
  1151.  
  1152. Boolean Expressions and Variables
  1153.  
  1154. 47. What is the right type to use for boolean values in C?  Why isn't it
  1155.     a standard type?  Should #defines or enums be used for the true and
  1156.     false values?
  1157.  
  1158. A:  C does not provide a standard boolean type, because picking one
  1159.     involves a space/time tradeoff which is best decided by the
  1160.     programmer.  (Using an int for a boolean may be faster, while using
  1161.     char will probably save data space.)
  1162.  
  1163.     The choice between #defines and enums is arbitrary and not terribly
  1164.     interesting.  Use any of
  1165.  
  1166.          #define TRUE  1             #define YES 1
  1167.          #define FALSE 0             #define NO  0
  1168.  
  1169.          enum bool {false, true};    enum bool {no, yes};
  1170.  
  1171.     as long as you are consistent within one program or project.  (The
  1172.     enum may be preferable if your debugger expands enum values when
  1173.     examining variables.)
  1174.  
  1175.     Some people prefer variants like
  1176.  
  1177.          #define TRUE (1==1)
  1178.          #define FALSE (!TRUE)
  1179.  
  1180.     These don't buy anything (see below).
  1181.  
  1182. 48. Isn't #defining TRUE to be 1 dangerous, since any nonzero value is
  1183.     considered "true" in C?  What if a built-in boolean or relational
  1184.     operator "returns" something other than 1?
  1185.  
  1186. A:  It is true (sic) that any nonzero value is considered true in C, but
  1187.     this applies only "on input", i.e. where a boolean value is
  1188.     expected.  When a boolean value is generated by a built-in operator,
  1189.     it is guaranteed to be 1 or 0.  Therefore, the test
  1190.  
  1191.          if((a == b) == TRUE)
  1192.  
  1193.     will succeed (if a, in fact, equals b and TRUE is one), but this
  1194.     code is obviously silly.  In general, explicit tests against TRUE
  1195.     and FALSE are undesirable, because some library functions (notably
  1196.     isupper, isalpha, etc.) return, on success, a nonzero value which is
  1197.     _not_ necessarily 1.  A good rule of thumb is to use TRUE and FALSE
  1198.     (or the like) only for assignment to a Boolean variable or as the
  1199.     return value from a Boolean function, never in a comparison.
  1200.  
  1201.     Preprocessor macros like TRUE and FALSE (and, in fact, NULL) are
  1202.     used for code readability, not because the underlying values might
  1203.     ever change.  That "true" is 1 and "false" (and source-code null
  1204.     pointers) 0 is guaranteed by the language.  (See also question 7.)
  1205.  
  1206.     References: K&R I Sec. 2.7 p. 41; K&R II Sec. 2.6 p. 42, Sec. A7.4.7
  1207.     p. 204, Sec. A7.9 p. 206; ANSI X3.159-1989 Secs. 3.3.3.3, 3.3.8,
  1208.     3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, 3.6.5 .
  1209.  
  1210. 49. What is the difference between an enum and a series of preprocessor
  1211.     #defines?
  1212.  
  1213. A:  At the present time, there is little difference.  Although many
  1214.     people might have wished otherwise, the ANSI standard says that
  1215.     enums may be freely intermixed with integral types, without errors.
  1216.     (If such intermixing were disallowed without explicit casts,
  1217.     judicious use of enums could catch certain programming errors.)
  1218.  
  1219.     The advantages of enums are that the numeric values are
  1220.     automatically assigned, that a debugger may be able to display the
  1221.     symbolic values when enum variables are examined, and that a
  1222.     compiler may generate nonfatal warnings when enums and ints are
  1223.     indiscriminately mixed (such mixing can still be considered bad
  1224.     style even though it is not strictly illegal) or when enum cases are
  1225.     left out of switch statements.
  1226.  
  1227.     References: K&R II Sec. 2.3 p. 39, Sec. A4.2 p. 196; H&S Sec. 5.5
  1228.     p. 100; ANSI X3.159-1989 Secs. 3.1.2.5, 3.5.2, 3.5.2.2 .
  1229.  
  1230. Operating System Dependencies
  1231.  
  1232. 50. How can I read a single character from the keyboard without waiting
  1233.     for a newline?
  1234.  
  1235. A:  Contrary to popular belief and many people's wishes, this is not a
  1236.     C-related question.  The delivery of characters from a "keyboard" to
  1237.     a C program is a function of the operating system, and cannot be
  1238.     standardized by the C language.  If you are using curses, use its
  1239.     cbreak() function.  Under UNIX, use ioctl to play with the terminal
  1240.     driver modes (CBREAK or RAW under "classic" versions; ICANON,
  1241.     c_cc[VMIN] and c_cc[VTIME] under System V or Posix systems).  Under
  1242.     MS-DOS, use getch().  Under other operating systems, you're on your
  1243.     own.  Beware that some operating systems make this sort of thing
  1244.     impossible, because character collection into input lines is done by
  1245.     peripheral processors not under direct control of the CPU running
  1246.     your program.
  1247.  
  1248.     Operating system specific questions are not appropriate for
  1249.     comp.lang.c .  Several common questions are answered in frequently-
  1250.     asked questions postings in the comp.unix.questions and
  1251.     comp.sys.ibm.pc newsgroups.
  1252.  
  1253. 51. How can I find out if there are characters available for reading
  1254.     (and if so, how many)?  Alternatively, how can I do a read that will
  1255.     not block if there are no characters available?
  1256.  
  1257. A:  These, too, are entirely operating-system-specific.  Depending on
  1258.     your system, you may be able to use "nonblocking I/O", or a system
  1259.     call named "select", or the FIONREAD ioctl, or O_NDELAY, or a
  1260.     kbhit() routine.
  1261.  
  1262. 52. How can my program discover the complete pathname to the executable
  1263.     file from which it was invoked?
  1264.  
  1265. A:  Depending on the operating system, argv[0] may contain all or part
  1266.     of the pathname.  (It may also contain nothing.)  You may be able to
  1267.     duplicate the command language interpreter's search path logic to
  1268.     locate the executable if the name in argv[0] is incomplete.
  1269.     However, there is no guaranteed or portable solution.
  1270.  
  1271. 53. How can a process change an environment variable in its caller?
  1272.  
  1273. A:  In general, it cannot.  If the calling process is prepared to listen
  1274.     explicitly for some indication that its environment should be
  1275.     changed, a special-case scheme can be set up.  (Under Unix, a child
  1276.     process cannot directly affect its parent at all.  Other operating
  1277.     systems have different process environments which could
  1278.     intrinsically support such communication.)
  1279.  
  1280. Stdio
  1281.  
  1282. 54. Why does errno contain ENOTTY after a call to printf?
  1283.  
  1284. A:  Many implementations of the stdio package adjust their behavior
  1285.     slightly depending on whether stdout is a terminal or not.  To make
  1286.     this determination, these implementations perform an operation which
  1287.     fails (with ENOTTY) if stdout is not a terminal.  Although the
  1288.     output operation goes on to complete successfully, errno still
  1289.     contains ENOTTY.  This behavior can be mildly confusing, but it is
  1290.     not strictly incorrect, because it is only meaningful for a program
  1291.     to inspect the contents of errno after an error has occurred (that
  1292.     is, after a library function that sets errno on error has returned
  1293.     an error code).
  1294.  
  1295. 55. My program's prompts and intermediate output don't always show up on
  1296.     my screen, especially when I pipe the output through another
  1297.     program.
  1298.  
  1299. A:  It is best to use an explicit fflush(stdout) at any point within
  1300.     your program at which output should definitely be visible.  Several
  1301.     mechanisms attempt to perform the fflush for you, at the "right
  1302.     time," but they do not always work, particularly when stdout is a
  1303.     pipe rather than a terminal.
  1304.  
  1305. 56. When I read from the keyboard with scanf(), it seems to hang until I
  1306.     type one extra line of input.
  1307.  
  1308. A:  scanf() was designed for free-format input, which is seldom what you
  1309.     want when reading from the keyboard.  In particular, "\n" in a
  1310.     format string does not mean "expect a newline", it means "discard
  1311.     all whitespace".  But the only way to discard all whitespace is to
  1312.     continue reading the stream until a non-whitespace character is seen
  1313.     (which is then left in the buffer for the next input), so the effect
  1314.     is that it keeps going until it sees a nonblank line.
  1315.  
  1316. 57. So what should I use instead?
  1317.  
  1318. A:  You could use a "%c" format, which will read one character that you
  1319.     can then manually compare against a newline; or "%*c" and no
  1320.     variable if you're willing to trust the user to hit a newline; or
  1321.     "%*[^\n]%*c" to discard everything up to and including the newline.
  1322.     Or you could use fgets() to read a whole line, and then use sscanf()
  1323.     or other string functions to parse the line buffer.
  1324.  
  1325. Miscellaneous
  1326.  
  1327. 58. Can someone tell me how to write itoa (the inverse of atoi)?
  1328.  
  1329. A:  Just use sprintf.
  1330.  
  1331. 59. I know that the library routine localtime will convert a time_t into
  1332.     a broken-down struct tm, and that ctime will convert a time_t to a
  1333.     printable string.  How can I perform the inverse operations of
  1334.     converting a struct tm or a string into a time_t?
  1335.  
  1336. A:  ANSI C specifies a library routine, mktime, which converts a
  1337.     struct tm to a time_t.  Several public-domain versions of this
  1338.     routine are available if your compiler does not support it yet.
  1339.  
  1340.     Converting a string to a time_t is harder, because of the wide
  1341.     variety of date and time formats which should be parsed.  Public-
  1342.     domain routines have been written for performing this function, as
  1343.     well, but they are less likely to become standardized.
  1344.  
  1345.     References: K&R II Sec. B10 p. 256; H&S Sec. 20.4 p. 361; ANSI
  1346.     X3.159-1989 Sec. 4.12.2.3 .
  1347.  
  1348. 60. I seem to be missing the system header file <sgtty.h>.  Can someone
  1349.     send me a copy?
  1350.  
  1351. A:  Standard headers exist in part so that definitions appropriate to
  1352.     your compiler, operating system, and processor can be supplied.  You
  1353.     cannot just pick up a copy of someone else's header file and expect
  1354.     it to work, unless that person uses exactly the same environment.
  1355.     Ask your vendor why the file was not provided (or to send another
  1356.     copy, if you've merely lost it).
  1357.  
  1358. 61. Does anyone know of a program for converting Pascal (Fortran, lisp,
  1359.     "Old" C, ...) to C?
  1360.  
  1361. A:  Several public-domain programs are available:
  1362.  
  1363.     p2c             written by Dave Gillespie, and posted to
  1364.                     comp.sources.unix in March, 1990 (Volume 21).
  1365.  
  1366.     ptoc            another comp.sources.unix contribution, this one
  1367.                     written in Pascal (comp.sources.unix, Volume 10,
  1368.                     also patches in Volume 13?).
  1369.  
  1370.     f2c             jointly developed by people from Bell Labs,
  1371.                     Bellcore, and Carnegie Mellon.  To find about f2c,
  1372.                     send the message "send index from f2c" to
  1373.                     netlib@research.att.com or research!netlib.
  1374.  
  1375.     FOR_C           Available from:
  1376.                                     Cobalt Blue
  1377.                                     2940 Union Ave., Suite C
  1378.                                     San Jose, CA  95124
  1379.                                     (408) 723-0474
  1380.  
  1381.     Promula.Fortran Available from
  1382.                                     Promula Development Corp.
  1383.                                     3620 N. High St., Suite 301
  1384.                                     Columbus, OH 43214
  1385.                                     (614) 263-5454
  1386.  
  1387.     The comp.sources.unix archives also contain converters between
  1388.     "K&R" C and ANSI C.
  1389.  
  1390. 62. Where can I get copies of all these public-domain programs?
  1391.  
  1392. A:  If you have access to Usenet, see the regular postings in the
  1393.     comp.sources.unix and comp.sources.misc newsgroups, which describe,
  1394.     in some detail, the archiving policies and how to retrieve copies.
  1395.     Otherwise, you can try anonymous ftp and/or uucp from a central,
  1396.     public-spirited site, such as uunet.uu.net, but this article cannot
  1397.     track or list all of the available sites and how to access them.
  1398.  
  1399. 63. How can I call Fortran (BASIC, Pascal, ADA, LISP) functions from C?
  1400.     (And vice versa?)
  1401.  
  1402. A:  The answer is entirely dependent on the machine and the specific
  1403.     calling sequences of the various compilers in use, and may not be
  1404.     possible at all.  Read your compiler documentation very carefully;
  1405.     sometimes there is a "mixed-language programming guide," although
  1406.     the techniques for passing arguments correctly are often arcane.
  1407.  
  1408. 64. Why don't C comments nest?  Are they legal inside quoted strings?
  1409.  
  1410. A:  Nested comments would cause more harm than good, mostly because of
  1411.     the possibility of accidentally leaving comments unclosed by
  1412.     including the characters "/*" within them.  For this reason, it is
  1413.     usually better to "comment out" large sections of code, which might
  1414.     contain comments, with #ifdef or #if 0.
  1415.  
  1416.     The character sequences /* and */ are not special within double-
  1417.     quoted strings, and do not therefore introduce comments, because a
  1418.     program (particularly one which is generating C code as output)
  1419.     might want to print them.
  1420.  
  1421. 65. I'm having trouble with a Turbo C program which crashes and says
  1422.     something like "floating point not loaded."
  1423.  
  1424. A:  Some compilers for small machines, including Turbo C and Ritchie's
  1425.     original pdp11 compiler, attempt to leave out floating point support
  1426.     if it looks like it will not be needed.  In particular, the non-
  1427.     floating-point versions of printf and scanf save space by not
  1428.     including code to handle %e, %f, and %g.  Occasionally the
  1429.     heuristics for "is the program using floating point?" are
  1430.     insufficient, and the programmer must insert one dummy explicit
  1431.     floating-point operation to force loading of floating-point support.
  1432.     Unfortunately, an apparently common sort of program (thus the
  1433.     frequency of the question) uses scanf to read, and/or printf to
  1434.     print, floating-point values upon which no arithmetic is done, which
  1435.     elicits the problem under Turbo C.
  1436.  
  1437.     In general, questions about a particular compiler are inappropriate
  1438.     for comp.lang.c .  Problems with PC compilers, for instance, will
  1439.     find a more receptive audience in a PC newsgroup.
  1440.  
  1441. 66. Does anyone have a C compiler test suite I can use?
  1442.  
  1443. A:  Plum Hall, (1 Spruce Ave., Cardiff, NJ 08232, USA), among others,
  1444.     sells one.
  1445.  
  1446. 67. Where can I get a YACC grammar for C?
  1447.  
  1448. A:  Several grammars are floating around; keep your eyes open.  There is
  1449.     one on uunet.uu.net (192.48.96.2) in net.sources/ansi.c.grammar.Z .
  1450.     FSF's GNU C compiler contains a grammar, as does the appendix to
  1451.     K&R II.  Several have recently been posted to the net.
  1452.  
  1453. 68. Where can I get the "Indian Hill Style Guide" and other coding
  1454.     standards?
  1455.  
  1456. A:  Various standards are available for anonymous ftp from:
  1457.          site                      file/directory
  1458.  
  1459.          cs.washington.edu         ~ftp/pub/cstyle.tar.Z
  1460.          (128.95.1.4)
  1461.  
  1462.          cs.toronto.edu            doc/programming
  1463.  
  1464.          giza.cis.ohio-state.edu   pub/style-guide
  1465.  
  1466.          prep.ai.mit.edu           pub/gnu/standards.text
  1467.  
  1468. 69. Where can I get extra copies of this list?
  1469.  
  1470. A:  For now, just pull it off the net; it is normally posted on about
  1471.     the first of the month, with an Expiration: line which should keep
  1472.     it around all month.  Eventually, it may be available for anonymous
  1473.     ftp, or via a mailserver.
  1474.  
  1475.  
  1476. Thanks to Mark Brader, Joe Buehler, Christopher Calabrese, Stephen M.
  1477. Dunn, Tony Hansen, Guy Harris, Karl Heuer, Blair Houghton, Kirk Johnson,
  1478. Andrew Koenig, John Lauro, Christopher Lott, Rich Salz, Joshua Simons,
  1479. and Erik Talvola, who have contributed, directly or indirectly, to this
  1480. article.
  1481.  
  1482.                                              Steve Summit
  1483.                                              scs@adam.mit.edu
  1484.                                              scs%adam.mit.edu@mit.edu
  1485.  
  1486. This article is Copyright 1988, 1990 by Steve Summit.
  1487. It may be freely redistributed so long as the author's name, and this
  1488. notice, are retained.
  1489. The C code in this article (vstrcat, error, etc.) is public domain and
  1490. may be used without restriction.
  1491.  
  1492.